package com.teichmann;

import java.io.IOException;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;

import com.teichmann.bo.Car;
import com.teichmann.bo.History;
import com.teichmann.engine.OnlineExecutor;


@SuppressWarnings("serial")
public class BuscaCarrosServlet extends HttpServlet {
	
	Logger logger = Logger.getLogger(this.getClass().getSimpleName());
	
	public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {

		execute(req, resp);
	}

	public void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws IOException, ServletException {

		execute(req, resp);
		
	}

	private void execute(HttpServletRequest request, HttpServletResponse response)
			throws IOException {
		String modelo 	= request.getParameter("modelo[]");
		String[] origens = request.getParameterValues("origem[]");

		if (!StringUtils.isEmpty(modelo)) {
			
			logger.info("modelo = "+ modelo);
			logger.info("crawlers = "+ origens);
			
			HttpSession session = request.getSession();
			session.removeAttribute(session.getId());

			OnlineExecutor oe = new OnlineExecutor(modelo, origens);
			List<Car> cars =  oe.execute();

			History.getInstance().addQuery(modelo, cars.size());
			
			session.setAttribute(session.getId(), cars);
			session.setMaxInactiveInterval(30);
			

			response.setHeader("Cache-Control","no-cache");
			response.setHeader("Pragma","no-cache");
			response.setDateHeader ("Expires", 0); 
		}
	}

}
